<template>
  <div class="root">
    <m-header title="最美自拍">
      <div slot="left" v-on:click="$router.go(-1)"><img class="m-icon-img margin-right-10" src="../assets/images/menu_back.png" /></div>
      <div slot="right"><img class="m-icon-img margin-right-10" src="../assets/images/menu_more.png" /></div>
    </m-header>

    <div class="content">

      <div class="price-box">
        <p class="price-title">围观价格：</p>
        <mu-text-field hintText="别人要花多少钱才能看您的自拍" v-model.number="price" />
      </div>

      <div class="selfie">
        <div class="image-wrapper" v-for="(item,index) in photoList" v-bind:style="{backgroundImage: 'url(' + item.avatar + ')'}"
          @click="viewImage(item.avatar)">
        </div>

        <label for="filechooser" class="image-wrapper add-icon">
        </label>
        <!--<input id="filechooser" type="file" accept="image/*;" capture="camera" style="display:none;" />-->
        <input id="filechooser" type="file" accept="image/*;" style="display:none;" />
      </div>

      <div class="buttonCon">
        <mu-raised-button label="完成" class="raised-button" backgroundColor="#02a588" @click="setPrice" />
      </div>
    </div>
  </div>



</template>

<script>
  import mHeader from '../components/header'
  import util from '../util/util.js'

  export default {
    components: {
      mHeader
    },
    data() {
      var price;
      return {
        price,
      }
    },
    computed: {
      photoList: function () {
        return this.$store.state.mySecretInfo.avatarList;
      }
    },

    methods: {

      viewImage(_url) {
        this.$router.push({
          name: 'ViewImage',
          query: {
            imgUrl: _url,
          }
        });
      },
      setPrice() {
        if (this.price < 0) return util.toast('请输入正确的金额');
        if (this.price === this.$route.query.selfiePrice) {
          console.log('价格未变')
          this.$router.go(-1);
          return;
        }
        var _this = this;
        this.$http.post('user/selfavatar/price', {
          amount: _this.price
        }).then(
          function (response) {
            if (response.data.code === '0') {
              // util.toast(response.data.msg);
            }
            _this.$router.go(-1);
          }
        );
      },

      bindUploadEvent() {
        var _this = this;
        var filechooser = document.getElementById('filechooser');
        var previewer = document.getElementById('previewer');
        // 200 KB 对应的字节数
        var maxsize = 200 * 1024;

        filechooser.onchange = function () {
          var files = this.files;
          var file = files[0];

          // 接受 jpeg, jpg, png 类型的图片
          if (!/\/(?:jpeg|jpg|png)/i.test(file.type)) {
            return util.toast('不支持的文件格式');
          }

          var reader = new FileReader();

          //onload是一个异步回调，当文件读取完执行该方法内代码
          reader.onload = function () {
            var result = this.result;
            _this.compressDataURL(result);
          };

          reader.readAsDataURL(file);
        };
      },

      //压缩并裁剪
      compressDataURL(dataURL) {
        var _this = this;
        const img = new window.Image();
        // onload
        img.onload = function () {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          //   canvas.width = 100 * ratio.width;
          //   canvas.height = 100 * ratio.height;
          const maxH = 800;
          if (img.height > maxH) {
            img.width *= maxH / img.height;
            img.height = maxH;
          }

          canvas.width = img.width;
          canvas.height = img.height;

          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0, img.width, img.height);

          const ndata = canvas.toDataURL('image/jpeg', 0.92);
          _this.uploadImg(ndata);
        };
        img.src = dataURL;
      },

      uploadImg(dataUrl) {
        var _this = this;
        const blob = this.dataURLtoBlob(dataUrl);
        const formData = new FormData();
        formData.append('avatar', blob);

        let xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
          //服务器连接已建立
          if (xhr.readyState === 1) {
            _this.$store.dispatch('showLoading');
          }
          //请求已完成，且响应已就绪
          if (xhr.readyState === 4) {
            _this.$store.dispatch('hideLoading');
            if (xhr.status === 200) {
              // 上传成功，获取到结果 results
              console.log(xhr.responseText);
              let response = JSON.parse(xhr.responseText);
              util.toast(response.msg);
              if (response.code === '0') {
                if (response.data.userAvatar !== null) {
                  _this.photoList.push(response.data.userAvatar);
                }
              }
            } else {
              // 上传失败
              util.toast('网络异常');
            }
          }
        };
        // let ulr = 'http://120.24.89.166:520/ar-social/api/user/base/avatar';
        let url = util.getHost() + '/ar-social/api/user/base/avatar';
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Authorization', this.$store.state.token);
        xhr.send(formData);
      },

      dataURLtoBlob(dataURL) {
        let binaryString = atob(dataURL.split(',')[1]);
        let arrayBuffer = new ArrayBuffer(binaryString.length);
        let intArray = new Uint8Array(arrayBuffer);
        let mime = dataURL.split(',')[0].match(/:(.*?);/)[1]

        for (let i = 0, j = binaryString.length; i < j; i++) {
          intArray[i] = binaryString.charCodeAt(i);
        }

        let data = [intArray];
        let result = new Blob(data, {
          type: mime
        });
        console.log(result);
        return result;
      },

      setPhotoType() {
        console.log('setPhotoType type=1');
        var url = 'jsbridge://setSelectType?type=1';
        var iframe = document.createElement('iframe');
        iframe.style.width = '1px';
        iframe.style.height = '1px';
        iframe.style.display = 'none';
        iframe.src = url;
        document.body.appendChild(iframe);
        setTimeout(function () {
          iframe.remove();
        }, 100);
      }
    },
    mounted() {
      this.bindUploadEvent();
      this.setPhotoType();
      this.price = this.$route.query.selfiePrice;
    }
  }

</script>

<style lang="less" scoped>
  /*@import "../assets/less/common.less";*/

  .price-box {
    margin: 8px;
    padding: 16px 16px 8px 16px;
    background-color: white;
    .price-title {
      font-size: 16px;
      color: #333333;
    }
  }

  .selfie {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    padding: 0 1%;
    .image-wrapper {
      width: 23%;
      height: 0px;
      padding-bottom: 23%;
      margin: 1%;
      /* 关键部分 */
      /*background-image: url(../assets/test.jpg);*/
      background-repeat: no-repeat;
      background-position: center center;
      /* 指定图片自动缩放大小 */
      -webkit-background-size: cover;
      background-size: cover;
      /* 指定使用padding-box区域显示背景图片 */
      -webkit-background-origin: padding-box;
      background-origin: padding-box;
    }
    .add-icon {
      background-image: url(../assets/images/secret_add_pic.png)
    }
  }

</style>
